package com.myssm.mybatis.org.apache.ibatis.configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.myssm.mybatis.org.apache.ibatis.io.Resources;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XmlConfigBuilder {

    private Configuration configuration;

    public XmlConfigBuilder(Configuration configuration){
        this.configuration=configuration;
    }

    //解析mybatis-config文件，构造configuration
    public Configuration parseMyBatisConfig(InputStream inputStream) throws DocumentException {
        SAXReader reader=new SAXReader();
        Document document = reader.read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> list = rootElement.selectNodes("//dataSource/property");

        //解析dataSource配置
        //用于存放解析dataSource的配置信息
        Properties properties=new Properties();
        for(Element element:list){
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }
        DruidDataSource dataSource=new DruidDataSource();
        dataSource.setDriverClassName(properties.getProperty("driverClass"));
        dataSource.setUrl(properties.getProperty("jdbcUrl"));
        dataSource.setUsername(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(dataSource);

        //获取mapper.xml的路径配置,并映射xxxMapper.xml文件，使用XmlMapperBuilder来获取MappedStatement
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for(Element mapper:mapperList){
            String resource = mapper.attributeValue("resource");
            InputStream mapperInputStream = Resources.getResourceAsStream(resource);
            XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
            xmlMapperBuilder.parse(mapperInputStream);
        }
        System.out.println("----------------mybatis-config.xml解析完毕---------------");
        return configuration;
    }
}
